using System;
using System.Collections.Generic;
using System.Linq;
using Locator.Common.DataAccess.Interface;
using Locator.Common.Model;

namespace Locator.Common.UnitTests
{
    public class InMemoryRepository<T> : IRepository<T> where T : class, IEntity
    {

        public InMemoryRepository()
            : this(Enumerable.Empty<T>())
        {

        }

        /// <summary>
        /// Initializes a new instance of the InMemoryRepository class.
        /// </summary>
        public InMemoryRepository(IEnumerable<T> entities)
        {
            this.set = new HashSet<T>();
            foreach (var entity in entities)
            {
                this.set.Add(entity);
            }

            this.queryableSet = set.AsQueryable();
        }

        public IQueryable<T> FindAll()
        {
            return this.queryableSet;
        }

        public IQueryable<T> FindWhere(System.Linq.Expressions.Expression<Func<T, bool>> predicate)
        {
            return this.queryableSet.Where(predicate);
        }

        public T FindById(int id)
        {
            return this.queryableSet.Single(o => o.Id == id);
        }

        public void Add(T entity)
        {
            this.set.Add(entity);
        }

        public void Remove(T entity)
        {
            this.set.Remove(entity);
        }

        private readonly HashSet<T> set;
        private readonly IQueryable<T> queryableSet;
    }
}
